#!/usr/bin/env python
# $Id: add_items.py 2 2008-04-04 18:53:47Z benchline $

from page import page
import sys, time, urllib
import db 

class add(page):

	def __init__(self):
		page.__init__(self)
		self.headingstr = "Add Items"
		self.db1 = db.db()
		self.upcdb1 = db.upcdb()

	def render(self):
		self.logic()
		self.encoding()
		self.html()

	def fix_date(self, date):
		datel = date.split("-")
		if len(datel) == 3:
			return "-".join(datel[:2])
		else:
			return date

	def logic(self):
		if request.has_key("cancel"):
			raise HTTP_REDIRECTION, "menu.py"
		if request.has_key("submit") and request["upc"][0]:
			upc = request["upc"][0]
			date = self.fix_date(request["date"][0])
			count = request["count"][0]
			if self.db1.upc_type_there(upc):
				self.log("upc_type is there for %s" % upc)
				for item in range(int(count)):
					self.db1.add_upc(upc, date)
					self.log("added %s to upcs" % upc)
				args = urllib.urlencode({'m': "%s container(s) of '%s' have been added to your foodstorage." % (count, self.db1.get_upc_type(upc))})
				raise HTTP_REDIRECTION, "add_items.py?%s" % args
			else:
				self.log("upc_type is not there for %s" % upc)
				if self.upcdb1.upc_there(upc):
					self.log("%s is in upcdatabase.com" % upc)
					desc = self.upcdb1.desc
					amt  = self.upcdb1.amt
					raise HTTP_REDIRECTION, "select_type.py?%s" % urllib.urlencode({"upc":upc,"date":date,"amt":amt,"desc":desc,"count":count})
				else:
					self.log("%s is not in upcdatabase.com" % upc)
					raise HTTP_REDIRECTION, "add_upcdb.py?%s" % urllib.urlencode({"upc":upc,"date":date,"count":count})

	def form(self):
		form = """
		<form name="add" method="POST" action="add_items.py">
		<table style="text-align: left; width: 20%%;" border="0" cellpadding="2" cellspacing="2">
		<tbody>
		<tr>
			<td>UPC</td>
			<td><input type=text name=upc></td>
		</tr>
		<tr>
			<td>Purchase Date</td>
			<td><input type=text name=date value="%s"></td>
		</tr>
		<tr>
			<td>Count</td>
			<td><input type=text name=count value="1"></td>
		</tr>
		<tr>
			<td><input name=submit type=submit value="Submit"></td>
			<td><input type=submit name=cancel value="Menu"></td>
		</tr>
		<script>document.forms.add.upc.focus();</script>
		</tbody>
		</table>
		</form>
		""" % time.strftime("%Y-%m")
		print form

	def message(self):
		if request.has_key("m"):
			message = request["m"][0]
			if message:
				print message

	def body(self):
		self.start_body()
		self.heading()
		self.form()
		self.message()
		self.footer()
		self.end_body()

class runner:
	def _test(self):
		add().render()

	def _doctest(self):
		import doctest
		doctest.testmod()

if __name__ == "__main__":
	r = runner()
	getattr(r, "_"+sys.argv[1])()
else:
	add().render()
